﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeSoft.Application.Bussiness;
using LeSoft.Application.Code;
using LeSoft.Application.Entity;
using LeSoft.Util;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Util;
using ZXing;
using System.Drawing;
using System.IO;
using System.Text;
using LeSoft.Application.Cache;

namespace LeSoft.Application.Web.Areas.ResourceManage.Controllers
{
    public class RS_PublicAreaController : MvcControllerBase
    {
        private PollingBLL pollingBLL = new PollingBLL();
        private OrganizeCache organizeCache = new OrganizeCache();
        //
        // GET: /ResourceManage/RS_PublicArea/
        #region 视图

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult Form()
        {
            return View();
        }

        [HttpGet]
        [HandlerAuthorize(PermissionMode.Enforce)]
        [HandlerAction(OperationType.Visit)]
        public ActionResult RelationOIForm()
        {
            return View();
        }
        #endregion


        #region 查询数据

        [HttpGet]
        [HandlerAction(OperationType.GetList,"公共区域","GetPageListJson")]
        public ActionResult GetPageListJson(Pagination pagination, string queryJson)
        {
            var watch = CommonHelper.TimerStart();
            var dataPstruct = new PStructBLL().GetPageList(pagination, queryJson);
            var data = from a in dataPstruct join b in pollingBLL.GetList() on a.Id equals b.PStructID into temp from tt in temp.DefaultIfEmpty() select tt;
            var JsonData = new
            {
                rows = data,
                total = pagination.total,
                page = pagination.page,
                records = pagination.records,
                costtime = CommonHelper.TimerEnd(watch)
            };
            return Content(JsonData.ToJson());
        }

        [HttpGet]
        [HandlerAction(OperationType.GetForm, "公共区域", "GetFormJson")]
        public ActionResult GetFormJson(string keyValue)
        {
            var data = pollingBLL.GetEntity(keyValue);
            return Content(data.ToJson());
        }


        /// <summary>
        /// 查询巡检点列表
        /// </summary>
        /// <param name="parentid"></param>
        /// <param name="condition"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAction(OperationType.GetList, "公共区域", "GetListJson")]
        public ActionResult GetListJson(string parentName, string SearchKeyWord)
        {
            var data = pollingBLL.GetList(parentName).OrderBy(t => t.ModifyDate).ToList();
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(SearchKeyWord))
            {
                data = data.FindAll(t => t.EnCode.Contains(SearchKeyWord) || t.Name.Contains(SearchKeyWord));
            }
            return Content(data.ToJson());
        }

        [HttpGet]
        [HandlerAction(OperationType.GetList, "公共区域", "GetHtml")]
        public ActionResult GetHtml(string SearchKeyWord, string parentId)
        {
            var data = pollingBLL.GetList().OrderBy(t => t.CreateDate).ToList();
            if (!string.IsNullOrEmpty(parentId))
            {
                data = data.Where(t => t.ParentId == parentId).ToList();
            }
            if (!OperatorProvider.Provider.Current().IsSystem)
            {
                var organizeids = organizeCache.GetSonOrganizeId(OperatorProvider.Provider.Current().CompanyId);
                data = data.Where(t => organizeids.Contains(t.OrganizeId)).ToList();
            }
            if (!string.IsNullOrEmpty(SearchKeyWord))
            {
                data = data.FindAll(t => t.EnCode.Contains(SearchKeyWord) || t.Name.Contains(SearchKeyWord));
            }
            StringBuilder _Html = new StringBuilder();
            var index = 1;
            foreach (var item in data)
            {
                _Html.Append("<tr><td>" + index + "</td><td>" + item.EnCode + "</td><td>" + item.Name + "</td>");
                switch (item.FlagWay)
                {
                    case 0: _Html.Append("<td>无标识</td>"); break;
                    case 1: _Html.Append("<td>rfid芯片</td>"); break;
                    case 2: _Html.Append("<td>条码</td>"); break;
                    case 3: _Html.Append("<td>二维码</td>"); break;
                    case 4: _Html.Append("<td>beacon</td>"); break;
                    default:
                        break;
                }
                _Html.Append("<td>" + item.FlagNo + "</td><td>" + item.PSAllName + "</td>");
                if (item.AuditMark == 1)
                    _Html.Append("<td><i class='fa fa-check fa-2x' style='color:green;margin-left:10px;' ><i/></td>");
                else
                    _Html.Append("<td></td>");
                _Html.Append("<td><button type='button' class='btn btn-sm btn-success' onclick='btn_addItem(\"" + item.PCode + "\",\"" + item.OrganizeId + "\")'><i class='fa fa-plus'></i> 关联巡检对象</button><button type='button' class='btn btn-sm btn-warning' onclick='btn_edit(\"" + item.PCode + "\",\"" + item.AuditMark + "\")'><i class='fa fa-pencil'></i> 编辑</button><button type='button' class='btn btn-sm btn-danger' onclick='btn_delete(\"" + item.PCode + "\")'><i class='fa fa-trash-o'></i> 删除</button></td>");
                index++;
            }
            var model = data.OrderByDescending(t => t.ModifyDate).FirstOrDefault();
            var obj = new { Html = _Html.ToString(), ModifyDate = model == null ? null : model.ModifyDate != null ? model.ModifyDate : model.CreateDate, Count = data.Count() };
            return Content(obj.ToJson());
        }


     




        #endregion
        #region 保存数据

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="pollingAreaEntity"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]       
        [HandlerAction(OperationType.Create, "公共区域", "SaveForm")]
        public ActionResult SaveForm(string keyValue, PollingAreaEntity pollingAreaEntity)
        {
            pollingBLL.SaveAForm(keyValue, pollingAreaEntity);
            return Success("操作成功。");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        [AjaxOnly]      
        [HandlerAction(OperationType.Delete, "公共区域", "RemoveForm")]
        public ActionResult RemoveForm(string keyValue)
        {
            pollingBLL.RemoveAForm(keyValue);
            return Success("删除成功。");
        }



        /// <summary>
        /// 产生一维码
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>

        public string GetBaCode(string guid)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.ITF;
            // writer.Options = options;  
            DateTime DateStart = new DateTime(1970, 1, 1, 8, 0, 0);
            TimeSpan timeStamp = System.DateTime.Now - DateStart;
            string code = "";
            if (string.IsNullOrEmpty(guid))
            {
                code = timeStamp.TotalSeconds.ToString("f4");
                Random rad = new Random();//实例化随机数产生器rad；

                code = code.Replace(".", "");

                int value = rad.Next(1000, 10000);
                code += value.ToString();

            }
            else
            {
                code = guid;
            }
            if (code.Length > 18)
            {
                code = code.Substring(0, 18);
            }
            Bitmap bitmap = writer.Write(code);
            string str = SaveImg(System.Web.HttpContext.Current.Request.MapPath("/Files/QRCode"), bitmap);
            code += "," + str;
            return code;
        }


        /// <summary>
        /// 根据链接获取二维码
        /// </summary>
        /// <param name="link">链接</param>
        /// <returns>返回二维码图片</returns>
        public string GetDimensionalCode(string guid)
        {
            string str = "";
            string code = "";
            Bitmap bmp = null;
            try
            {
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeScale = 4;
                //int version = Convert.ToInt16(cboVersion.Text);
                qrCodeEncoder.QRCodeVersion = 7;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                if (string.IsNullOrEmpty(guid))
                {
                    code = Guid.NewGuid().ToString("N");
                }
                else
                {
                    code = guid;
                }

                bmp = qrCodeEncoder.Encode(code);
                string sPath = System.Web.HttpContext.Current.Request.MapPath("/Files/QRCode");
                str = SaveImg(sPath, bmp);
                code += "," + str;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Invalid version !");
            }

            return code;
        }



        /// <summary>  
        /// 保存图片  
        /// </summary>  
        /// <param name="strPath">保存路径</param>  
        /// <param name="img">图片</param>  
        /// 
        public string SaveImg(string strPath, Bitmap img)
        {
            //文件名称  
            string guid = Guid.NewGuid().ToString().Replace("-", "") + ".png";
            //保存图片到目录  
            if (Directory.Exists(strPath))
            {

                img.Save(strPath + "/" + guid, System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                //当前目录不存在，则创建  
                Directory.CreateDirectory(strPath);
            }
            return guid;
        }



        #endregion
    }
}
